package com.issac.controller;

import com.issac.entity.Student;
import com.issac.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Collection;
import java.util.List;

@RestController
@RequestMapping("/student")
public class StudentHandler {
    @Autowired
    private StudentRepository studentRepository;

    @GetMapping("/findAll")
    public Collection<Student> findAll(){
        return studentRepository.findAll();
    }

    @GetMapping("/findById/{id}")
    public Student findById(@PathVariable("id") long id){
        return studentRepository.findById(id);
    }
    @PostMapping("/add")
    public void add(@RequestBody Student student){
        studentRepository.add(student);
    }
    @PutMapping("/update")
    public void update(@RequestBody Student student){
        studentRepository.update(student);
    }
    @DeleteMapping("/DeleteById/{id}")
    public void deleteById(@PathVariable("id") long id){
        studentRepository.deleteById(id);
    }
    @GetMapping("/validator")
    public void validatorUser(@Valid Student student, BindingResult bindingResult){
        System.out.println(student);
        if (bindingResult.hasErrors()){
            List<ObjectError> list = bindingResult.getAllErrors();
            for (ObjectError objectError:list) {
                System.out.println(objectError.getCode()+"-"+objectError.getDefaultMessage());
            }
        }

    }
}
